# -*- coding: utf-8 -*-
from MysqlHelp import DB
import pymysql
import GetMysql
from math import cos, sin, atan2, sqrt, radians, degrees

def get_date():
    str_frequency = '107.7'
    res =GetMysql.get_deviceids(str_frequency)
    print(res)
    pointlist = []
    for i in res[0]:
        result = get_point(i)
        pointlist.append(result)
    res_point = center_geolocation(pointlist)
    print( res_point)


def center_geolocation( geolocations):
        """
        输入多个经纬度坐标，找出中心点
        :param geolocations: 集合
        :return: 
        """
        x = 0
        y = 0
        z = 0
        length = len(geolocations)
        print(geolocations)
        for i in geolocations:
            lon = radians(float(i['lon']))
            lat = radians(float(i['lat']))
            x += cos(lat) * cos(lon)
            y += cos(lat) * sin(lon)
            z += sin(lat)

        x = float(x / length)
        y = float(y / length)
        z = float(z / length)

        return (degrees(atan2(y, x)), degrees(atan2(z, sqrt(x * x + y * y))))

def get_point(deviceid):
    conn = pymysql.connect(host="47.92.33.19", user="root", password="1qazxsw2", database="database_fm", charset="utf8")
    # 得到一个可以执行SQL语句的光标对象
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    sql = 'SELECT lon,lat from fm_t_device WHERE phy_id = '+deviceid+';'
    try:

        # 关闭光标对象
        cursor.execute(sql)
        sql_result = cursor.fetchall()
        # resultdict = {}
        # for i in sql_result:
        #     resultdict[i[0]]=i[1]
        return sql_result[0]
    except Exception as ex:
        raise ex
    finally:
        cursor.close()
        # 关闭数据库连接
        conn.close()

if __name__ == '__main__':
    get_date()   